﻿using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.FinanceManage;
using SmartWMS.EntityFramework;
using SmartWMS.Server.FinanceManage.ReceivablesServices.Dto;
using SmartWMS.Server.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.FinanceManage.ReceivablesServices
{
    /// <summary>
    /// 应收管理服务层
    /// </summary>
    public class ReceivablesServices:IReceivablesServices
    {
        /// <summary>
        ///  财务应收
        /// </summary>
        private readonly IRepository<Collection> _collectionrepository;
        private readonly IRepository<PayType> _paytyperepository;
        private readonly SmartWMSContext _dbcontext;
        public ReceivablesServices(IRepository<Collection> collectionrepository, SmartWMSContext dbcontext, IRepository<PayType> paytyperepository)
        {
            _collectionrepository = collectionrepository;
            _dbcontext = dbcontext;
            _paytyperepository = paytyperepository;
        }
        /// <summary>
        /// 财务应收信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<List<CollectionDto>>> GetCustomList(Selcollection input)
        {
            var list = (from a in _dbcontext.Collection
                        join b in _dbcontext.PayType on a.TypeId equals b.Id
                        select new CollectionDto
                        {
                            id = a.Id,
                            SerialNumber = a.SerialNumber,
                            Name = a.Name,
                            TypeId = a.TypeId,
                            TypeName = b.TypeName,
                            Payer = a.Payer,
                            Receivable = a.Receivable,
                            NetReceipts = a.NetReceipts,
                            Residue = a.Receivable - a.NetReceipts,
                            PayInstitution = a.PayInstitution,
                            LastPaymentDate = a.LastPaymentDate,
                            State = a.State
                        }).ToList();
            if (!string.IsNullOrEmpty(input.SerialNumber))
            {
                list = list.Where(m => m.SerialNumber.Contains(input.SerialNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(input.Name))
            {
                list = list.Where(m => m.Name.Contains(input.Name)).ToList();
            }
            if (!string.IsNullOrEmpty(input.Payer))
            {
                list = list.Where(m => m.Payer.Contains(input.Payer)).ToList();
            }
            if (input.KLastPaymentDate != null)
            {
                list = list.Where(m => m.LastPaymentDate <= input.KLastPaymentDate).ToList();
            }
            if (input.JLastPaymentDate != null)
            {
                list = list.Where(m => m.LastPaymentDate >= input.JLastPaymentDate).ToList();
            }
            if (!string.IsNullOrEmpty(input.TypeId.ToString()))
            {
                list = list.Where(m => m.TypeId == input.TypeId).ToList();
            }
            if (!string.IsNullOrEmpty(input.State.ToString()))
            {
                list = list.Where(m => m.State == input.State).ToList();
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount / (double)input.pagesize);
            list = list.Skip((input.pageindex - 1) * input.pagesize).Take(input.pagesize).ToList();
            var response = list.MapToList<CollectionDto>();
            return response != null ? Response<List<CollectionDto>>.Ok(response, totalCount, pageCount) : Response<List<CollectionDto>>.Fail("查询失败");
        }
        /// <summary>
        /// 财务类别下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<PayType>>> GetCustom()
        {
            var list = await _paytyperepository.GetAllListAsync();
            var result = list.MapToList<PayType>();
            return Response<List<PayType>>.Ok(result);
        }
        /// <summary>
        /// 应收金额信息添加
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddCollection(Collection info)
        {
            var list = await _collectionrepository.GetAllListAsync();
            var Collectioninfo = list.Where(m => m.Name == info.Name).FirstOrDefault();
            if (Collectioninfo != null)
            {
                return Response<bool>.Fail("产品类别编码已存在");
            }
            info.NetReceipts = 0;
            info.Residue = info.Receivable;
            info.LastPaymentDate = DateTime.Now;
            info.State = 1;
            info.Reviewer = "孙先生";
            info.Opinion = "无";
            info.Audittime = DateTime.Now;
            info.CreateTime = DateTime.Now;
            var entity = info.MapTo<Collection>();
            await _collectionrepository.InsertAsync(entity);
            return Response<bool>.Ok(true);
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns> 
        public async Task<Response<bool>> BatchDelSuppiler(CollectionDto info)
        {
            var sid = info.ids.Split(',');
            var list = new List<Collection>();
            foreach (var item in sid)
            {
                var pList = _collectionrepository.GetListQuery().Where(t => t.Id == int.Parse(item));
                list.AddRange(pList);
            }
            var result = await _collectionrepository.DeleteAsync(list);
            return result > 0 ? Response<bool>.Ok(result > 0) :
                 Response<bool>.Fail(result > 0);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DelSuppiler(CollectionDto info)
        {
            var list = await _collectionrepository.GetAllListAsync();
            var suppilerinfo = list.Where(m => m.Id == info.id).FirstOrDefault();
            var result = await _collectionrepository.DeleteByIdAsync(suppilerinfo);
            return result > 0 ? Response<bool>.Ok(result > 0) :
                 Response<bool>.Fail(result > 0);
        }
        /// <summary>
        /// 反填应收金额信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns> 
        public async Task<Response<CollectionDto>> GetSupplierById(CollectionDto info)
        {
            var list = await _collectionrepository.GetAllListAsync();
            var suppilerinfo = list.Where(m => m.Id == info.id).FirstOrDefault();
            var result = suppilerinfo.MapTo<CollectionDto>();
            return Response<CollectionDto>.Ok(result);
        }
        /// <summary>
        /// 修改应收金额信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns> 
        public async Task<Response<bool>> UpdateSuppiler(CollectionDto info)
        {
            var suppilerinfo = info.MapTo<Collection>();
            var list = _collectionrepository.GetListQuery();
            var existingSupplier = list.FirstOrDefault(x => x.Name == info.Name && x.Id != info.id);
            if (existingSupplier != null)
            {
                return Response<bool>.Ok(false, 1, "名称已存在");
            }
            var result = await _collectionrepository.UpdateAsync(suppilerinfo);

            return Response<bool>.Ok(result > 0 ? true : false);
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> Updatestate(CollectionDto info)
        {
            var suppilerinfo = info.MapTo<Collection>();
            var list = _collectionrepository.GetListQuery();
            var existingSupplier = list.FirstOrDefault(m => m.Id == info.id);
            if (info.stateid == 1)
            {
                existingSupplier.State = 2;
            }
            else
            {
                existingSupplier.State = 3;
            }
            var result = await _collectionrepository.UpdateAsync(existingSupplier);
            return Response<bool>.Ok(result > 0 ? true : false);
        }
        /// <summary>
        /// 付款
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> Updpayment(CollectionDto info)
        {
            var suppilerinfo = info.MapTo<Collection>();
            var list = _collectionrepository.GetListQuery();
            var existingSupplier = list.FirstOrDefault(m => m.Id == info.id);
            existingSupplier.PayInstitution = info.PayInstitution;
            existingSupplier.State = 4;
            var result = await _collectionrepository.UpdateAsync(existingSupplier);
            return Response<bool>.Ok(result > 0 ? true : false);
        }
    }
}
